
<template>
  <div class="asset-category-form">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>{{ isEdit ? '编辑资产档案' : '新建资产档案' }}</span>
          <el-button @click="handleBack">返回</el-button>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
        class="asset-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="资产分类" prop="category">
              <el-select v-model="formData.category" placeholder="请选择资产分类" style="width: 100%">
                <el-option label="固定资产" value="fixed" />
                <el-option label="低值易耗品" value="low_value" />
                <el-option label="租赁资产" value="lease" />
                <el-option label="租入固定资产改良" value="lease_improvement" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资产编码" prop="code">
              <el-input v-model="formData.code" placeholder="系统自动生成" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="资产名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入资产名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格型号" prop="model">
              <el-input v-model="formData.model" placeholder="请输入规格型号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="使用部门" prop="department">
              <el-select v-model="formData.department" placeholder="请选择使用部门" style="width: 100%">
                <el-option label="财务部" value="finance" />
                <el-option label="行政部" value="admin" />
                <el-option label="技术部" value="tech" />
                <el-option label="市场部" value="marketing" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="使用人" prop="user">
              <el-input v-model="formData.user" placeholder="请输入使用人" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="存放位置" prop="location">
              <el-input v-model="formData.location" placeholder="请输入存放位置" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资产状态" prop="status">
              <el-select v-model="formData.status" placeholder="请选择资产状态" style="width: 100%">
                <el-option label="在用" value="in_use" />
                <el-option label="闲置" value="idle" />
                <el-option label="维修中" value="maintenance" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="购置日期" prop="purchaseDate">
              <el-date-picker
                v-model="formData.purchaseDate"
                type="date"
                placeholder="请选择购置日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资产价值" prop="value">
              <el-input-number
                v-model="formData.value"
                :min="0"
                :precision="2"
                placeholder="请输入资产价值"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="formData.category === 'fixed'">
          <el-col :span="12">
            <el-form-item label="用友编号" prop="yyCode">
              <el-input v-model="formData.yyCode" placeholder="财务人员关联用友编号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="现状描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入资产现状描述"
          />
        </el-form-item>

        <el-form-item label="资产图片">
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :file-list="fileList"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-change="handleChange"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button v-if="!isEdit" @click="submitAndPrint">提交并打印标签</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const formRef = ref()
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const fileList = ref([])

// 判断是否为编辑模式
const isEdit = computed(() => route.name === 'AssetCategoryEdit')

// 表单数据
const formData = reactive({
  id: '',
  category: '',
  code: '',
  name: '',
  model: '',
  department: '',
  user: '',
  location: '',
  status: 'in_use',
  purchaseDate: '',
  value: 0,
  yyCode: '', // 用友编号
  description: '',
  images: []
})

// 表单验证规则
const rules = reactive({
  category: [
    { required: true, message: '请选择资产分类', trigger: 'change' }
  ],
  name: [
    { required: true, message: '请输入资产名称', trigger: 'blur' }
  ],
  model: [
    { required: true, message: '请输入规格型号', trigger: 'blur' }
  ],
  department: [
    { required: true, message: '请选择使用部门', trigger: 'change' }
  ],
  user: [
    { required: true, message: '请输入使用人', trigger: 'blur' }
  ],
  location: [
    { required: true, message: '请输入存放位置', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择资产状态', trigger: 'change' }
  ],
  purchaseDate: [
    { required: true, message: '请选择购置日期', trigger: 'change' }
  ],
  value: [
    { required: true, message: '请输入资产价值', trigger: 'blur' }
  ]
})

// 初始化表单数据
const initFormData = () => {
  if (isEdit.value) {
    // 编辑模式，加载资产数据
    const assetId = route.params.id
    // 这里应该从API获取资产数据
    // 模拟数据
    Object.assign(formData, {
      id: assetId,
      category: 'fixed',
      code: 'ZC20230001',
      name: '笔记本电脑',
      model: 'ThinkPad X1 Carbon',
      department: 'tech',
      user: '张三',
      location: '总部A座501',
      status: 'in_use',
      purchaseDate: '2023-01-15',
      value: 8500,
      yyCode: 'YY20230001',
      description: '技术部开发用笔记本电脑，配置较高',
      images: ['laptop1.jpg', 'laptop2.jpg']
    })

    // 模拟图片列表
    fileList.value = [
      {
        name: 'laptop1.jpg',
        url: 'https://picsum.photos/seed/laptop1/400/300.jpg'
      },
      {
        name: 'laptop2.jpg',
        url: 'https://picsum.photos/seed/laptop2/400/300.jpg'
      }
    ]
  } else {
    // 新建模式，生成资产编码
    formData.code = 'ZC' + new Date().getFullYear() + String(Math.floor(Math.random() * 10000)).padStart(4, '0')
  }
}

// 返回列表
const handleBack = () => {
  router.push('/asset-categories')
}

// 提交表单
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      // 处理图片数据
      formData.images = fileList.value.map(file => {
        if (file.url) {
          return file.url
        } else if (file.response) {
          return file.response.url
        }
        return ''
      }).filter(Boolean)

      // 实际应该调用API保存数据
      console.log('表单数据：', formData)
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
      router.push('/asset-categories')
    }
  })
}

// 重置表单
const resetForm = () => {
  formRef.value.resetFields()
  fileList.value = []
  if (!isEdit.value) {
    formData.code = 'ZC' + new Date().getFullYear() + String(Math.floor(Math.random() * 10000)).padStart(4, '0')
  }
}

// 提交并打印标签
const submitAndPrint = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      // 处理图片数据
      formData.images = fileList.value.map(file => {
        if (file.url) {
          return file.url
        } else if (file.response) {
          return file.response.url
        }
        return ''
      }).filter(Boolean)

      // 实际应该调用API保存数据
      console.log('表单数据：', formData)
      ElMessage.success('创建成功')

      // 打印标签
      ElMessage.success('正在打印资产标签...')
      // 实际应该调用打印功能

      router.push('/asset-categories')
    }
  })
}

// 图片预览
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}

// 移除图片
const handleRemove = (file, fileList) => {
  console.log(file, fileList)
}

// 图片变化
const handleChange = (file, fileList) => {
  console.log(file, fileList)
}

// 页面加载时初始化数据
onMounted(() => {
  initFormData()
})
</script>

<style scoped>
.asset-category-form {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.asset-form {
  max-width: 900px;
  margin: 0 auto;
}
</style>
